package org.cmg.study.spring;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author CMG
 * @version 1.0
 * @cLassName JdkProxy
 * @description JDK动态代理实现InvocationHandler接口
 * @date 2021/9/1 10:12
 **/
public class JdkProxy implements InvocationHandler {
    /**
     * 需要代理的目标对象
     */
    private Object target;
    final MyAspect myAspect = new MyAspect();

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        myAspect.myBefore();
        Object result = method.invoke(target, args);
        myAspect.myAfter();
        return result;
    }

    /**
     * 定义获取代理对象的方法
     * @param targetObject
     * @return
     */
    private Object getJdkProxy(Object targetObject){
        //为目标对象target赋值
        this.target = targetObject;
        //JDK动态代理只能代理实现了接口的类，从newProxyInstance函数所需的参数就可以看出来
        return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(), targetObject.getClass().getInterfaces(), this);
    }

    public static void main(String[] args) {
        //实例化JDKProxy对象
        JdkProxy jdkProxy = new JdkProxy();
        //获取代理对象
        IUserManager user = (IUserManager) jdkProxy.getJdkProxy(new UserManagerImpl());
        user.addUser("cmg", "123456");
        user.delUser("cmg");
    }
}
